package com.carleasoft.mps.cms.business.article.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carleasoft.mps.cms.business.article.bean.entity.AuthorityCategoryEntity;
import com.carleasoft.mps.cms.business.article.bean.po.CategoryInsertPo;
import com.carleasoft.mps.cms.business.article.bean.po.CategoryPo;
import com.carleasoft.mps.cms.business.article.constants.ExceptionCMSEnum;
import com.carleasoft.mps.cms.business.article.constants.StatusEnum;
import com.carleasoft.mps.cms.business.article.dao.CategoryDao;
import com.carleasoft.mps.cms.business.article.service.CategoryService;
import com.carleasoft.mps.cms.business.article.bean.vo.CategoryNameTreeVo;
import com.carleasoft.mps.cms.utils.TreeUtil;
import com.carleasoft.mps.core.exceptions.BusinessException;
import com.carleasoft.mps.core.user.ThreadUserContext;
import com.carleasoft.mps.core.user.UserCacheData;
import com.carleasoft.mps.core.utils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, AuthorityCategoryEntity> implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;


    /**
     * 修改
     * @param categoryInsertPo
     * @param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCategory(CategoryInsertPo categoryInsertPo) {
        //  获取用户信息
        UserCacheData loginUserInfo = ThreadUserContext.getCurrentCacheUser();
        if(categoryInsertPo.getCategoryCode() ==null) {
            throw new BusinessException(ExceptionCMSEnum.CATEGORY_NULL);
        }
        AuthorityCategoryEntity authorityCategoryEntity = ConvertUtils.sourceToTarget(categoryInsertPo, AuthorityCategoryEntity.class);
        if ("0".equals(categoryInsertPo.getParentCode())){
            authorityCategoryEntity.setFullPath(categoryInsertPo.getCategoryCode());
        }else{
            authorityCategoryEntity.setFullPath(categoryInsertPo.getParentFullPath()+"&"+categoryInsertPo.getCategoryCode());
        }
        //校验是否存在子栏目和文章
        if(categoryInsertPo.getStatus() != null && (categoryInsertPo.getStatus() == 1 ||
                authorityCategoryEntity.getStatus() == 2 )) {
            selectSubtopicOrArticle(authorityCategoryEntity);
        }

        //校验是否和其他栏目名称冲突
        AuthorityCategoryEntity entity = categoryDao.selectOne(Wrappers.<AuthorityCategoryEntity>lambdaQuery()
                .eq(AuthorityCategoryEntity::getCategoryName, authorityCategoryEntity.getCategoryName())
                .ne(AuthorityCategoryEntity::getCategoryCode,categoryInsertPo.getCategoryCode()));
        if (Objects.nonNull(entity)){
            throw new BusinessException(ExceptionCMSEnum.CATEGORY_NOT_ONE);
        }
        authorityCategoryEntity.setUpdateTime(LocalDateTime.now());
        authorityCategoryEntity.setUpdateBy(loginUserInfo.getUserName());
        categoryDao.update(authorityCategoryEntity,Wrappers.<AuthorityCategoryEntity>lambdaUpdate().eq(AuthorityCategoryEntity::getCategoryCode,authorityCategoryEntity.getCategoryCode()));
    }


    /**
     * 栏目树
     * @return
     */
    @Override
    public List<CategoryNameTreeVo> findAllCategoryTree(CategoryPo categoryPo) {
        List<CategoryNameTreeVo> allCategoryTree = categoryDao.findAllCategoryTree(categoryPo);
        if (categoryPo.getStatus()==null){
            if (StrUtil.isNotBlank(categoryPo.getKeyword())){
                return allCategoryTree;
            }else {
                return TreeUtil.getInstance().enquireTree(allCategoryTree);
            }
        }else {
            return allCategoryTree;
        }
    }

    @Override
    public List<CategoryNameTreeVo> categoryTree(CategoryPo categoryPo) {
        LambdaQueryWrapper<AuthorityCategoryEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AuthorityCategoryEntity::getStatus, StatusEnum.NORMAL.getId());
        wrapper.eq(AuthorityCategoryEntity::getSiteCode,categoryPo.getSiteCode());
        wrapper.orderByDesc(AuthorityCategoryEntity::getWeight);
        List<AuthorityCategoryEntity> authorityCategoryEntities = categoryDao.selectList(wrapper);
        List<CategoryNameTreeVo> categoryNameTreeVos = ConvertUtils.sourceToTarget(authorityCategoryEntities, CategoryNameTreeVo.class);
        return TreeUtil.getInstance().enquireTree(categoryNameTreeVos);
    }



    /**
     * 栏目新增
     * @param categoryInsertPo
     * @param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertCategory(CategoryInsertPo categoryInsertPo) {
        //  获取用户信息
        UserCacheData loginUserInfo = ThreadUserContext.getCurrentCacheUser();

        //判断是否存在相同栏目
        AuthorityCategoryEntity categoryEntity = categoryDao.selectOne(Wrappers.<AuthorityCategoryEntity>lambdaQuery().eq(AuthorityCategoryEntity::getCategoryName, categoryInsertPo.getCategoryName()));
        if (categoryEntity != null){
            throw new BusinessException(ExceptionCMSEnum.CATEGORY_NOT_ONE);
        }
        String code = UUID.randomUUID().toString().replaceAll("-", "");
        if(StringUtils.isBlank(categoryInsertPo.getSiteCode())) {
            throw new BusinessException(ExceptionCMSEnum.SITE_NULL);
        }
        if (StringUtils.isBlank(categoryInsertPo.getCategoryName())) {
            throw new BusinessException(ExceptionCMSEnum.CATEGORY_NULL);
        }

        AuthorityCategoryEntity authorityCategoryEntity = ConvertUtils.sourceToTarget(categoryInsertPo, AuthorityCategoryEntity.class);
        if (authorityCategoryEntity.getContentModel() == null) {
            throw new BusinessException(ExceptionCMSEnum.CONTENT_MODEL);
        }
        String fullPath = null;
        if(StrUtil.isBlank(authorityCategoryEntity.getParentCode())){
            authorityCategoryEntity.setParentCode(StatusEnum.NORMAL.getId().toString());
            fullPath = code;
        }else {
            fullPath = categoryInsertPo.getParentFullPath()+"&"+code;
        }
        authorityCategoryEntity.setFullPath(fullPath);
        authorityCategoryEntity.setCategoryCode(code);
        authorityCategoryEntity.setCreateBy(loginUserInfo.getUserName());
        authorityCategoryEntity.setCreateTime(LocalDateTime.now());
        authorityCategoryEntity.setWeight(0);
        categoryDao.insert(authorityCategoryEntity);
    }

    @Override
    public int updateWeight(AuthorityCategoryEntity authorityCategoryEntity) {
        LambdaUpdateWrapper<AuthorityCategoryEntity> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(AuthorityCategoryEntity::getCategoryCode,authorityCategoryEntity.getCategoryCode());
        wrapper.set(AuthorityCategoryEntity::getWeight,authorityCategoryEntity.getWeight());
        return categoryDao.update(null,wrapper);
    }

    @Override
    public AuthorityCategoryEntity selectByCode(String categoryCode) {
        return categoryDao.selectOne(Wrappers.<AuthorityCategoryEntity>lambdaQuery().eq(AuthorityCategoryEntity::getCategoryCode,categoryCode));
    }

    @Override
    public String findByParentCode(String categoryCode) {
        List<AuthorityCategoryEntity> categoryEntitys =
                categoryDao.selectList(Wrappers.<AuthorityCategoryEntity>lambdaQuery().eq(AuthorityCategoryEntity::getParentCode, categoryCode));
        if(categoryEntitys != null || categoryEntitys.size() > 0){
            for (AuthorityCategoryEntity categoryEntity:categoryEntitys) {
                if ("最新政策".equals(categoryEntity.getCategoryName())){
                    return categoryEntity.getCategoryCode();
                }
                findByParentCode(categoryEntity.getCategoryCode());
            }
        }
        return  categoryCode;
    }

    public void selectSubtopicOrArticle(AuthorityCategoryEntity authorityCategoryEntity) {
        //查询是否存在子栏目和文章
        LambdaQueryWrapper<AuthorityCategoryEntity> query = Wrappers.lambdaQuery();
        query.eq(AuthorityCategoryEntity::getParentCode,authorityCategoryEntity.getCategoryCode());
        query.ne(AuthorityCategoryEntity::getStatus,StatusEnum.REMOVE.getId());
        List<AuthorityCategoryEntity> list = categoryDao.selectList(query);
        if(list.size() > 0) {
            throw new BusinessException(ExceptionCMSEnum.HAS_CATEGORY);
        }else {
            if(categoryDao.selectLevelOrArticle(authorityCategoryEntity.getCategoryCode()) > 0) {
                throw new BusinessException(ExceptionCMSEnum.HAS_ARTICLE);
            }
        }
    }

}
